<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:insert="common/header :: head"></head>
<!--课表管理-->
<style>
    #div1>div{margin-left: 10px;}
    #div2>div{margin-left: 10px;}
    #buttons{margin-top: 10px;margin-right: 40px;float: right;}
    .el-form-item__content{width: 400px;}
    .el-dialog{width: 550px;}
    .el-autocomplete{width: 350px;}
</style>
<body>
<div id="wrapper" v-cloak>
    <div style="float: left" >
        <div  id="div1" style="margin-block: 5px">
            <el-select size="small" v-model="course.year" placeholder="请选择年级"  @change="changeClassData" clearable>
                <el-option v-for="year in yearData" :key="year" :label=`${year}级` :value="'20'+year">
                </el-option>
            </el-select>

            <el-select size="small" v-model="course.mname" placeholder="请选择专业" @change="changeClassData" clearable>
                <el-option v-for="major in majorData" :key="major" :label="major" :value="major">
                </el-option>
            </el-select>

            <el-select size="small" v-model="course.cname" @change="$forceUpdate()" placeholder="请选择班级" clearable>
                <el-option v-for="cls in classData" :key="cls" :label="cls" :value="cls">
                </el-option>
            </el-select>

        </div>
        <div style="margin-bottom: 5px" id="div2">
            <el-select  size="small" v-model="course.week" placeholder="请选择周次" clearable>
                <el-option v-for="w in weekData" :key="w" :label=`第${w}周` :value="w">
                </el-option>
            </el-select>

            <el-select size="small"  v-model="course.classtime" placeholder="请选择课程节次" clearable>
                <el-option v-for="time in timeData2" :key="time" :label=`第${time}节` :value="time">
                </el-option>
            </el-select>
            <el-input v-model="course.name" size="small"  suffix-icon="el-icon-search" placeholder="请输入课程\教室\老师"   style="height:40px;line-height: 40px;width:205px" ></el-input>
        </div>
    </div>

    <div id="buttons">
        <el-button type="primary" size="small" @click="queryCourse('0')">查询</el-button>
        <el-button type="info" size="small" @click="clearInput">重置</el-button>
        <el-button type="primary" size="small"@click="showModifyWin">添加课程</el-button>
        <el-button type="warning" size="small" @click="showAddCourseExcel">导入课表</el-button>
        <!--        <el-button type="primary" size="small">下载模板</el-button>-->
    </div>

    <div style="margin-top: -25px; clear: both;">
        <!-- 使用ElementUI的分割线组件，用来创建一个分割线 -->
        <el-divider></el-divider>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" stripe style="width: 100%;margin-top: -19px;" :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}">
        <el-table-column prop="week" label="周次" width="100"></el-table-column>
        <el-table-column prop="date" label="上课日期" width="120">
            <template  slot-scope="scope">
                <span>{{scope.row.date.split(' ')[0]}}</span>
            </template>
        </el-table-column>
        <el-table-column prop="weekStr" label="星期" width="80"></el-table-column>
        <el-table-column prop="coursename" label="课程名" width="260"></el-table-column>
        <el-table-column prop="classtime" label="节次" width="110"></el-table-column>
        <el-table-column prop="classroom" label="教室" width="160"></el-table-column>
        <el-table-column prop="cname" label="班级" width="100"></el-table-column>
        <el-table-column prop="nickname" label="上课老师" width="130"></el-table-column>
        <el-table-column fixed="right" label="操作">
            <template  slot-scope="scope">
                <div v-if="caculateDiff(scope.row.date)">
                    <el-button  type="primary" @click="edit(scope.row)" size="mini" icon="el-icon-edit">编辑</el-button>
                    <el-popconfirm @onConfirm="del(scope.row)" title="确定删除？">
                        <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference" >删除</el-button>
                    </el-popconfirm>
                </div>
            </template>
        </el-table-column>
    </el-table>
    <!--    分页 -->
    <div style="text-align: right;background-color: white" >
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 10, 20, 40]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
    </div>

    <el-dialog title="添加或修改课程" :visible.sync="dialogFormVisible" :close-on-click-modal="false" @close="cancel">
        <el-form :model="editTableData" label-width="80px">
            <el-form-item label="课程名称" label-widh="150">
                <el-autocomplete v-model="editTableData.coursename" :fetch-suggestions="querySearchCourse" placeholder="请输入内容">
                </el-autocomplete>
            </el-form-item>

            <el-form-item label="老师名称" >
                <el-select  v-model="editTableData.nickname" placeholder="请选择教师" style="width: 350px;margin-bottom: 0px;" filterable>
                    <el-option v-for=" c in courseTeachers" :key="c.value" :label="c.value" :value="c.value">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="班级名称">
                <el-select  v-model="editTableData.cname" placeholder="请选择班级"
                            multiple style="width: 350px;margin-bottom: 0px;" filterable>
                    <el-option v-for=" cname in classData2" :key="cname.value" :label="cname.value" :value="cname.value">
                    </el-option>
                </el-select>
            </el-form-item>


            <el-form-item label="上课时间">
                <el-col :span="8">
                    <el-date-picker type="date" placeholder="选择日期" v-model="date1" style="width: 135px;"@change="selectWeek"></el-date-picker>
                </el-col>

                <el-select  v-model="liketime" placeholder="筛选条件上午\下午\晚上" @change="changeClasstime" style="margin-left: 5px;width: 213px">
                    <el-option v-for=" l in likeData" :key="l" :label="l" :value="l">
                    </el-option>
                </el-select>

                <el-select  v-model="editTableData.classtime" multiple
                            placeholder="请选择上课时间" style="width: 350px;margin-top: 15px" @change="isLiketime">
                    <el-option v-for=" t in timeData" :key=`第${t}小节` :label=`第${t}小节` :value=`第${t}小节`></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="教室" style="width: 150px;float: left">
                <el-autocomplete
                        style="width: 160px"
                        v-model="editTableData.classroom"
                        :fetch-suggestions="querySearchCourseNameAndClassroom"
                        placeholder="请输入内容">
                </el-autocomplete>
                &nbsp;&nbsp;&nbsp;周次&nbsp;&nbsp;<el-input style="width: 140px;" v-model="week" disabled></el-input>
            </el-form-item>
        </el-form>
        <p style="color: rgb(142, 154, 175);margin-top: 10%;text-align: left;margin-left: -20%;display: inline-block;">温馨提示: 请提前一天添加或修改课表</p>
        <div slot="footer" class="dialog-footer" style="clear:both;">
            <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
            <el-button size="small" type="primary" @click="save">确 定</el-button>
        </div>
    </el-dialog>
    <el-dialog   v-loading="loading"
                 element-loading-text="数据添加中,预计5-6分钟"
                 element-loading-spinner="el-icon-loading"
                 element-loading-background="rgba(0, 0, 0, 0.8)"
                 title="批量导入课程表"
                 :visible.sync="excelDialog"
                 width="40%" height="110%"
                 :close-on-click-modal="false">
        <el-form style="display: inline-block;margin-left: 30px">
            <el-upload class="upload-demo" ref="upload" multiple accept=".xls"
                       action="" :auto-upload="false" :show-file-list="true" :on-success="endUpload" :on-error="errorUp"
                       :before-upload="beforeUpload" :http-request="uploadFile" :limit="1">
                <el-button size="small" slot="trigger" type="primary">选择文件</el-button>
                <div slot="tip">请上传文件大小不超过2MB,格式为 .xls类型的文件</div>
            </el-upload>
        </el-form>
        <p style="margin-top: 20px;color: red;">可以使用教务系统中导出的全校性总课表(格式.et,另存为excel后导入),一次只能上传一个文件。</p>
        <div slot="footer" class="dialog-footer" style="display: flex">
            <el-button size="small" type="primary" @click="uploadExcel">确 定</el-button>
            <el-button size="small" @click="excelDialog = false">取 消</el-button>
        </div>
    </el-dialog>

</div>

<script>
    var v = new Vue({
        el:"#wrapper",
        data:{
            pageNumFlag : "0",//判断是否是点击页码来查询数据,0表示不是,1表示是
            course: {},
            pageNum: 1,
            pageSize: 10,
            total: 0,
            yearData:[],  //年级
            classData:[], //班级
            classData1:[], //班级1 中间件
            classData2:[], //班级2 中间件
            majorData:[], //专业
            tableData:[],
            dialogFormVisible : false,
            excelDialog : false,
            date:[],
            date1: new Date(),
            editTableData:{coursename:"",nickname:"",cname:"",classroom:"",week:"",date1: "",id:"",classtime:[]},
            courseNameData :[],
            courseTeachers: [],
            weekData: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30], //周次
            timeData:[1,2,3,4,5,6,7,8,9,10],
            timeData1:[1,2,3,4,5,6,7,8,9,10],
            timeData2:["1~2","3~4","5~6","7~8","9~10"],    //搜索条件
            uid:"",
            liketime:"",
            likeData:["上午","下午","晚上"],//上课时间筛选条件
            flag:0, //传递给后端与id一起判断是添加还是修改,如果是0则是添加,是1就是修改
            week:"",
            saveFlag:0,
            classroomData :[],//教室数组
            user:{}, //登录人的信息
            loading : false,
        },
        methods:{
            //计算当前时间与传过来的时间的的时间差,用于判断是否显示操作按钮
            caculateDiff(date){
                var timestamp1 = new Date().getTime();
                var timestamp2 =Date.parse(date.split(" ")[0]+" "+date.split(" ")[1]
                    .substr(date.indexOf(" ")+1),date.indexOf("~"));
                var diff = timestamp1 - timestamp2;
                if (diff>0){
                    return false;
                }else {
                    return true;
                }

            },
            //根据具体时间查询周次
            selectWeek(date){
                var time = this.formateDate(date).split(" ")[0];
                axios.get("../schedule/selectWeek?date="+time).then(res=>{
                    if (res.data){
                        this.week = '第'+res.data+'周';
                    }
                })
            },
            //判断是否选中了上午,下午,晚上
            isLiketime(){
                //如果liketime为undefined 则提示用户要先选择筛选条件
                if (!this.liketime){
                    this.editTableData.classtime ="";
                    this.$message({
                        type:"error",
                        message:"请先选择节次筛选条件",
                    })
                }
            },
            //根据上午,下午,晚上筛选课表
            changeClasstime(val){
                this.editTableData.classtime ="";
                this.timeData = this.timeData1;
                if (val == '上午'){
                    this.timeData = [1,2,3,4];
                }else if (val == '下午'){
                    this.timeData = [5,6,7,8];
                }else if (val == '晚上'){
                    this.timeData = [9,10];
                }
            },
            //模糊匹配教室
            querySearchCourseNameAndClassroom(queryString,cb){
                var str = queryString ? this.classroomData.filter(item=>item.value.toLowerCase()
                    .indexOf(queryString.toLowerCase())===0) : this.classroomData;
                cb(str);
            },
            //模糊匹配课程名称
            querySearchCourse(queryString,cb){
                var str = queryString ? this.courseNameData.filter(item=>item.value.toLowerCase()
                    .indexOf(queryString.toLowerCase())===0) : this.courseNameData;
                cb(str);
            },
            //查询老师
            queryTeachers(){
                axios.get("../schedule/queryTeachers").then(res=>{
                    //对newArray数组进行转换,每一个元素都转成json格式{value:"元素"}
                    var array = [];
                    for (let classNameElement of res.data) {
                        var json = {value: null };
                        json.value = classNameElement;
                        array.push(json);
                    }
                    this.courseTeachers = array;
                })
            },
            //每页行数
            handleSizeChange(val){
                this.pageSize = val;
                this.queryCourse();
            },
            //根据页码来查询
            handleCurrentChange(val){
                this.pageNum = val;
                this.pageNumFlag = "1";
                this.queryCourse();
            },
            //打开课表导入dialog框
            showAddCourseExcel(){
                this.excelDialog = true;
            },
            //上传excel文件
            uploadExcel(){
                const files = this.$refs.upload.uploadFiles;
                let size2M = files[0].size / 1024 / 1024 < 2;
                if (!size2M) {
                    this.$message.warning('上传大小不能超过2M!');
                    return false;
                }

                if (files >= 0) {
                    this.$message({message: "请选择文件后再点确定", type: "warning"})
                } else {
                    this.$refs.upload.submit()
                }
            },
            //before-upload 上传文件前
            beforeUpload: function (file) {
                if (['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].indexOf(file.type) == -1 && ['application/vnd.ms-excel'].indexOf(file.type) == -1) {
                    this.$message.error({message: "请上传.xls格式的文件", type: 'error'});
                    return false;
                }
            },
            //上传失败调用
            errorUp(err) {
                this.$message({message: err, type: "error"})
            },
            //上传成功调用
            endUpload() {
                this.queryCourse();
            },
            //文件上传
            async uploadFile(param) {
                const File = param.file;
                const service = axios.create({})
                let formData = new FormData()
                formData.append("file", File);
                this.loading = true;
                const res = await service({
                    url: '../schedule/upload',
                    method: 'POST',
                    transformRequest: [function (data, headers) {
                        // 去除post请求默认的Content-Type
                        delete headers.post['Content-Type']
                        return data
                    }],
                    data: formData
                }).then(res => {
                    if (res.data.code == 1) {
                        this.queryCourse();
                        this.excelDialog = false;
                        this.$message({message: '上传成功', type: "success"});
                        if (res.data.data.length !=0){
                            this.$alert(res.data.data+"等老师不存在,请在系统用户管理中添加后再次导入课表");
                        }
                        //添加成功后从第一页开始查询
                        this.clearInput();
                        this.pageNum = 1;
                        this.loading = false;
                        this.$refs.upload.clearFiles();
                    } else {
                        this.loading = false;
                        this.$message({showClose: true, duration: 10000, message: "系统异常,请联系管理", type: "error"});
                        this.$refs.upload.clearFiles();
                    }
                })
            },

            //查询年份和班级
            getYearAndClass(){
                axios.get("../schedule/getYearAndClass").then(res=>{
                    this.yearData = res.data.data.yearList;
                    this.classData = res.data.data.className;
                    this.classData1 = res.data.data.className;
                    var array = [];
                    for (let classNameElement of res.data.data.className) {
                        var json = {value: null };
                        json.value = classNameElement;
                        array.push(json);
                    }
                    this.classData2 = array;
                })
            },
            //根据年级和专业来渲染对应的班级
            changeClassData(){
                //清空班级的文本框
                this.course.cname = "" ;
                //重新导入班级数据列
                this.classData = this.classData1;

                axios.get("../schedule/selectClassByMajorAndYear",{
                    params:{
                        mname : this.course.mname || "",
                        year : this.course.year || ""
                    }
                }).then(res=>{
                    this.classData = res.data;
                })
            },

            //查询专业
            queryMajor(){
                axios.get("../schedule/queryMajor").then(res=>{
                    this.majorData = res.data.data;
                })
            },

            //查询周次和课程名称
            queryCourseNameAndClassroom(){
                axios.get("../schedule/queryCourseNameAndClassroom").then(res=>{
                    this.courseNameData = res.data.data.courseName;
                    this.classroomData = res.data.data.classroom;
                })
            },

            //查询课程
            queryCourse(data){
               this.pageNumFlag = data;
               var params = new URLSearchParams();
               //根据条件重置初始查询页数
                if (this.pageNumFlag == '0' &&(this.course.week != null || this.course.name != null || this.course.cname != null
                    || this.course.mname != null || this.course.year!= null || this.course.classtime != null )){
                    this.pageNum = 1;
                }
                params.append("year",this.course.year || '');    //年级
                params.append("mname",this.course.mname ||'');  //专业名称
                params.append("cname",this.course.cname ||'');  //班级名称
                params.append("week",this.course.week || '');    //周次
                params.append("name",this.course.name || '');    //课程名称\节次\教室\老师名称
                params.append("pageNum",(this.pageNum-1)*this.pageSize); //查询的起始位置
                params.append("pageSize",this.pageSize);                //从起始位置查询的数量
                params.append("classtime",this.course.classtime||'');
                var jsonData = {};
                for (var pair of params.entries()) {
                    jsonData[pair[0]] = pair[1];
                }
                axios.post("../schedule/queryCourse",jsonData).then(res=>{
                    if (res.data.code){
                        if (!res.data.data){
                            return;
                        }
                        this.tableData = res.data.data.data;
                        //给周次加上 第xx周
                        for (let index in this.tableData) {
                            this.tableData[index].week = '第'+ this.tableData[index].week + '周';
                            if(this.tableData[index].classtime.indexOf("~")!=-1){
                                this.tableData[index].classtime = '第' + this.tableData[index].classtime + '节';
                            }else {
                                this.tableData[index].classtime = '第' + this.tableData[index].classtime + '小节';
                            }
                        }
                        this.total = res.data.data.total;
                        //this.$message({showClose: true, message: '查询成功!', type: 'success'});
                    }
                })
            },
            //重置文本框
            clearInput(){
                this.course = {};
                this.classData = this.classData1;
            },
            //退出dialog框
            cancel(){
                //由于row是一个引用型的对象,所以修改editTableData中的数据会导致row中的数据被修改,如果是点了取消,则重新查询数据
                this.queryCourse();
                this.dialogFormVisible = false;
            },
            //添加,打开编辑的对话框
            showModifyWin(){
                this.editTableData = {coursename:"",nickname:"",cname:"",classroom:"",week:"",date1:"",classtime:""};
                this.date = "";
                this.liketime = "";
                this.dialogFormVisible = true;
            },
            //编辑课程
            edit(row){
                this.flag = 1;  //代表着修改
                this.dialogFormVisible =true;
                this.editTableData = row;
                //渲染周次
                this.week=row.week;
                var array = [];
                array.push(row.cname);
                this.editTableData.cname=array;
                this.editTableData.nickname = this.editTableData.nickname+' '+row.uid;
                //格式化时间
                var date = row.date.split(" ");
                this.date1 = date[0];
                this.editTableData.id = row.id;
                this.editTableData.week =row.week;
                //把 第1~2节 改成 数字字符串"1,2"
                var time =this.editTableData.classtime;
                time = time.substring(time.indexOf("第")+1,time.indexOf("节"));
                //使row的classtime数据变成一个数组
                this.editTableData.classtime = time.split("~");
                var morning = 0; //早上
                var afternoon = 0; //下午
                var night = 0; //晚上

                //根据选中的节次,计算筛选的时间段liketime
                for (let index in this.editTableData.classtime) {
                    if (this.editTableData.classtime[index]<=4){
                        morning++;
                    }else if (4<this.editTableData.classtime[index]&&this.editTableData.classtime[index]<=8){
                        afternoon++;
                    }else if (8<this.editTableData.classtime[index]&&this.editTableData.classtime[index]<=10){
                        night++;
                    }
                    if (morning==this.editTableData.classtime.length){

                        this.liketime = "上午";
                    }else if (afternoon==this.editTableData.classtime.length){
                        this.liketime = "下午";
                    }else if (night==this.editTableData.classtime.length){
                        this.liketime = "晚上";
                    }
                    //使节次在编辑框中显示为第xxx小节
                    if (this.editTableData.classtime[index].indexOf("小")==-1){
                        this.editTableData.classtime[index] = '第' +this.editTableData.classtime[index]+'小节';
                    }else {
                        this.editTableData.classtime[index] = '第' +this.editTableData.classtime[index]+'节';
                    }
                }
                //根据对应的筛选条件给日期赋值
                if (this.liketime == '上午'){
                    this.timeData = [1,2,3,4];
                }else if (this.liketime == '下午'){
                    this.timeData = [5,6,7,8];
                }else if (this.liketime == '晚上'){
                    this.timeData = [9,10];
                }
            },

            //添加或修改数据
            save(){
                this.saveFlag++;
                //截取week
                this.week = this.week.replaceAll(/第(\d{1,2})周/g,"$1");
                var p = new URLSearchParams();
                p.append("coursename",this.editTableData.coursename || "");
                p.append("nickname",this.editTableData.nickname || "");
                p.append("cname",this.editTableData.cname || "");
                p.append("date",this.formateDate(this.date1));
                p.append("create_by",this.user.username);
                p.append("update_by",this.user.username);

                var str = '';
                //把节次"第1小节,第2小节"改成"1,2"
                if (this.editTableData.classtime!=''){
                    var time = this.editTableData.classtime.join(",");
                    var array = time.split(",");
                    var newArray = [];
                    //获取节次数组,如[1,2]
                    for (let a of array) {
                        newArray.push(a.replaceAll(/第(\d{1,2})小节/g,"$1"));
                    }
                    str = newArray.join(",");
                }

                //将数组转成字符串
                p.append("classtime",str);
                p.append("classroom",this.editTableData.classroom ||"" );
                p.append("week",this.week || "" );
                p.append("id",this.editTableData.id|| "" );
                p.append("flag",this.flag);
                var count = 0;
                let json = {value:this.editTableData.coursename};
                for (let key in this.courseNameData) {
                    if (this.courseNameData[key].value != this.editTableData.coursename){
                        count ++;
                    }
                }
                if (count == this.courseNameData.length){
                    this.courseNameData.push(json);
                }

                //表单数据转json
                var jsonData = {};
                for (var pair of p.entries()) {
                    jsonData[pair[0]] = pair[1];
                }

                if (this.saveFlag>1){
                    return;
                }
                this.$message({message:"保存中请稍后!", type:"warning"});
                axios.post("../schedule/save",jsonData).then(res=>{
                    this.saveFlag = 0
                    if (res.data.code){
                        this.$message({message:res.data.msg, type:"success",});
                        this.dialogFormVisible = false;
                        //查询时，默认为查询第一页
                        this.pageNum = 1;
                    }else{
                        this.$message({message:res.data.msg, type:"error",});
                    }
                })
            },
            //删除课程
            del(row){
                row.week =row.week.substring(row.week.indexOf("第")+1,row.week.indexOf("周"));
                axios.post("../schedule/deleteCourse?",row).then(res=>{
                    if (res.data.code){
                        this.$message({
                            type:"success",
                            message:res.data.msg
                        });
                    }else{
                        this.$message({
                            type:"error",
                            message:res.data.msg
                        });
                    }
                    this.queryCourse();
                })
            },

            // 时间格式化 Tue Aug 01 2023 00:00:00 GMT+0800 (中国标准时间) 转 yyyy-mm-dd hh:mm:ss
            formateDate(date1){
                const dateString = "Tue Aug 01 2023 00:00:00 GMT+0800 (中国标准时间)";
                let time1 = new Date(date1);

                let year = time1.getFullYear();
                let month = time1.getMonth() + 1; // 月份从 0 开始，需要加 1
                let day = time1.getDate();

                const formattedTime = `${year}-${padNumber(month)}-${padNumber(day)}`;

                function padNumber(number) {
                    return number.toString().padStart(2, "0");
                }
                if (formattedTime.startsWith("NaN")){
                    return  "";
                }else{
                    return formattedTime;
                }
            },changeClassInfo(value){ //班级选择
                this.course.cname = value;
            }
        },
        created(){
            this.getYearAndClass();
            this.queryMajor();
            this.queryCourse();
            this.queryCourseNameAndClassroom();
            this.queryTeachers();
            this.selectWeek(new Date());
            this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {};

        },
        //调节表头为固定值
        mounted(){
            setTimeout(()=>{
                document.querySelector(".el-table__header").style.width = '100%';
                document.querySelector(".el-table__body").style.width = '100%';
            }, 100)
        }
    })
</script>
</body>
</html>